package P35.P704;

import org.junit.Test;

/**
 * @Author DJ同学
 * @Date 2021/2/27 11:59
 * @Version 1.0
 * @Name 二分查找
 * @Problem https://leetcode-cn.com/problems/binary-search/
 */
public class Solution {
    @Test
    public void test(){

        int i = search(new int[]{1, 3, 5, 6}, 5);
    }
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while(left<=right){
            //https://www.cnblogs.com/greatLong/p/10539624.html
            int mid = left+((right-left)>>1);//需要加括号 位移运算符优先级低于加减（如果没有加括号就会导致先进行left+...,再右边移动）
            if(nums[mid]==target){
                return mid;
            }else if(nums[mid]>target){
                right = mid-1;
            }else{
                left = mid+1;
            }
        }
        return -1;
    }
}
